import { register, login } from "../../../services/auth";
import { globalStore } from "../../../store/index";
import { toast } from "../../../utils/toast";
import { applyTabBar } from "../../../utils/tabBar";

Page({
  data: {
    mode: "login" as "login" | "register",
    account: "",
    password: "",
    nickname: "",
    role: "chef" as "chef" | "diner",
    loading: false,
    remember: false,
  },

  onLoad() {
    this.restoreRemembered();
  },

  onShow() {},

  switchMode(event: WechatMiniprogram.BaseEvent) {
    const mode = event.currentTarget.dataset.mode as "login" | "register";
    this.setData({ mode, password: "" });
  },

  handleAccount(event: WechatMiniprogram.CustomEvent<{ value: string }>) {
    this.setData({ account: event.detail.value.trim() });
  },

  handlePassword(event: WechatMiniprogram.CustomEvent<{ value: string }>) {
    this.setData({ password: event.detail.value });
  },

  handleNickname(event: WechatMiniprogram.CustomEvent<{ value: string }>) {
    this.setData({ nickname: event.detail.value.trim() });
  },

  handleRole(event: WechatMiniprogram.CustomEvent<{ value: string }>) {
    this.setData({ role: event.detail.value });
  },

  handleRememberChange(event: WechatMiniprogram.CustomEvent<{ value: string[] }>) {
    const value = event.detail?.value || [];
    const remember = Array.isArray(value) && value.includes("remember");
    this.setData({ remember });
    if (!remember) {
      this.clearRemembered();
    }
  },

  async handleSubmit() {
    if (this.data.loading) return;
    const { mode, account, password, nickname, role, remember } = this.data;
    if (!account || !password) {
      toast("请输入账号和密码");
      return;
    }
    if (mode === "register" && !nickname) {
      toast("请输入昵称");
      return;
    }
    this.setData({ loading: true });
    try {
      let result;
      if (mode === "register") {
        result = await register(account, password, role, nickname);
        globalStore.setUserProfile(result.user);
        this.setData({ remember: true });
        this.saveRemembered(account, password, role);
      } else {
        result = await login(account, password);
        globalStore.setUserProfile(result.user);
      }
      await globalStore.initAppData();
      if (remember || mode === "register") {
        this.saveRemembered(account, password, role);
      } else {
        this.clearRemembered();
      }
      wx.showToast({ title: "成功", icon: "success" });
      setTimeout(() => {
        const targetRole = globalStore.userProfile?.role;
        applyTabBar(targetRole === "chef" ? "chef" : targetRole === "diner" ? "diner" : "guest");
        if (targetRole === "chef") {
          wx.switchTab({ url: "/pages/user/cart/index" });
        } else {
          wx.switchTab({ url: "/pages/user/home/index" });
        }
      }, 300);
    } catch (error) {
      console.error("auth failed", error);
      toast((error as Error).message || "操作失败");
    } finally {
      this.setData({ loading: false });
    }
  },

  restoreRemembered() {
    try {
      const cached = wx.getStorageSync<{ account: string; password: string; role: "chef" | "diner" }>("cm_auth_remember");
      if (cached && cached.account && cached.password) {
        this.setData({
          account: cached.account,
          password: cached.password,
          role: cached.role || "chef",
          remember: true,
        });
      }
    } catch (error) {
      console.warn("restore remember failed", error);
    }
  },

  saveRemembered(account: string, password: string, role: "chef" | "diner") {
    try {
      wx.setStorageSync("cm_auth_remember", { account, password, role });
    } catch (error) {
      console.warn("save remember failed", error);
    }
  },

  clearRemembered() {
    try {
      wx.removeStorageSync("cm_auth_remember");
    } catch (error) {
      console.warn("clear remember failed", error);
    }
  },
});
